package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.ServerResponse;
import entity.User;
import service.IUserService;
import service.impl.UserServiceImpl;
import util.JSONUtil;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

	private IUserService userService = new UserServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		switch (method) {
		case "login":
			login(req, resp);
			break;
		case "logout":
			logout(req, resp);
			break;
			
		default:
			break;
		}
	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("user");
		if (user != null) {
			List<User> onLineUserList = (List<User>) getServletContext().getAttribute("onLineUserList");		
			onLineUserList.remove(user);
			
			session.invalidate();
			// 重定向到登录界面
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// 首先验证验证码对不对，验证码不对，后面的不需要验证
		String checkCode = req.getParameter("checkCode");
		// 将用户输入的验证码和后台生成的验证码比较
		String checkCodeSession = (String) req.getSession().getAttribute("checkCodeSession");
//		if ("" == checkCode
//			|| null == checkCode
//			|| checkCode.equals(checkCodeSession) == false) {
//			resp.sendRedirect(req.getContextPath() + "/login.jsp");
//			return;
//		}
		
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		User user = userService.login(name, password);
		
		if (null != user) {
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			
			List<User> onLineUserList = (List<User>) getServletContext().getAttribute("onLineUserList");
			if (null == onLineUserList) {
				onLineUserList = new ArrayList<User>();
				getServletContext().setAttribute("onLineUserList", onLineUserList);
			}
			onLineUserList.add(user);
			
			ServerResponse serverResponse = ServerResponse.createSuccess("登录成功");
			JSONUtil.obj2Json(resp, serverResponse);
		} else {
//			resp.sendRedirect(req.getContextPath() + "/fail.jsp");
			ServerResponse serverResponse = ServerResponse.createError("用户名或密码错误");
			JSONUtil.obj2Json(resp, serverResponse);
		}
	}
}
